import os
import yaml

def load_note_from_file(filename):
    try:
        with open(os.path.join('notes', filename), 'r', encoding='utf-8') as file:
            content = file.read()
            parts = content.split('---', 2)
            if len(parts) == 1:  # No '---' separator found
                note_data = {}
                content = parts[0].strip()
            else:
                note_data = yaml.safe_load(parts[1])
                content = parts[2].strip()
            title = filename
            tags = ','.join(note_data.get('tags', [])) if 'tags' in note_data else ''
            return title, tags, content, note_data
    except FileNotFoundError:
        print(f"Error: File {filename} not found.")
        return "Untitled", "", "", {}
    except yaml.YAMLError as e:
        print(f"Error parsing YAML in {filename}: {e}")
        return "Untitled", "", "", {}

def save_note_to_file(filename, content, tags, update=False):
    file_path = os.path.join('notes', filename)
    note_data = {
        'tags': tags.split(',')
    }
    with open(file_path, 'w', encoding='utf-8') as file:
        file.write(f"---\n{yaml.dump(note_data)}---\n{content}")
    return filename

def update_database_from_files():
    from models import db, Note
    existing_notes = {note.filename for note in Note.query.all()}
    files_in_dir = {file for file in os.listdir('notes') if file.endswith('.md')}
    new_files = files_in_dir - existing_notes
    removed_files = existing_notes - files_in_dir

    for file in new_files:
        title, tags, content, _ = load_note_from_file(file)
        new_note = Note(filename=file, tags=tags)
        db.session.add(new_note)

    for file in removed_files:
        Note.query.filter_by(filename=file).delete()

    db.session.commit()
